package cn.sightsnow.zh.util;

import cn.sightsnow.zh.entity.Route;
import cn.sightsnow.zh.repository.RouteRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
@Slf4j
@Component
public class RouteAutoCompleteTask {
    private final RouteRepository routeRepository;

    public RouteAutoCompleteTask(RouteRepository routeRepository) {
        this.routeRepository = routeRepository;
    }

    @Scheduled(fixedRate = 3600000) // 每小时执行一次
    public void autoCompleteRoutes() {
        List<Route> activeRoutes = routeRepository.findByStatus(1);

        activeRoutes.forEach(route -> {
            long hours = ChronoUnit.HOURS.between(route.getStartTime(), LocalDateTime.now());
//            long seconds = ChronoUnit.SECONDS.between(route.getStartTime(), LocalDateTime.now());
            if (hours >= 72) {
//                log.info("自动结束路径：{}，运行时间：{}秒", route.getRouteId(), seconds);
                log.info("自动结束路径：{}，运行时间：{}小时", route.getRouteId(), hours);
                route.setStatus(0);
                route.setEndTime(LocalDateTime.now());
                routeRepository.save(route);
            }
        });
    }
}
